package com.darcytech.debezium.core.work;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bettercloud.vault.VaultException;
import com.darcytech.debezium.common.secret.vault.VaultClient;

public class VaultHelper implements UserAndPassHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(VaultHelper.class);

    private final static String FIX_PREFIX = "mysql";

    private final VaultClient vaultClient;

    public VaultHelper(VaultClient vaultClient) {
        this.vaultClient = vaultClient;
    }

    @Override
    public String getUserName(String group, String hostName) {
        String path = FIX_PREFIX + "/" + hostName + "/" + group;
        String property = FIX_PREFIX + "." + hostName + "." + group + ".username";
        try {
            return vaultClient.getValue(path, property);
        } catch (VaultException e) {
            LOGGER.error(e.getMessage());
            return "";
        }

    }

    @Override
    public String getPassWord(String group, String hostName) {
        String path = FIX_PREFIX + "/" + hostName + "/" + group;
        String property = FIX_PREFIX + "." + hostName + "." + group + ".password";
        try {
            return vaultClient.getValue(path, property);
        } catch (VaultException e) {
            LOGGER.error(e.getMessage());
            return "";
        }
    }

    @Override
    public String getUserNameExpression(String group, String hostName) {
        String path = FIX_PREFIX + "/" + hostName + "/" + group;
        String property = FIX_PREFIX + "." + hostName + "." + group + ".username";
        return "${vault:" + path + ":" + property + "}";
    }

    @Override
    public String getPasswordExpression(String group, String hostName) {
        String path = FIX_PREFIX + "/" + hostName + "/" + group;
        String property = FIX_PREFIX + "." + hostName + "." + group + ".password";
        return "${vault:" + path + ":" + property + "}";
    }
}
